<?php
/**
* @package mosRest
* @author Chad Auld and Ozgur Cem Sen (code@brilaps.com)
* @copyright Brilaps, LLC (http://brilaps.com)
* @link http://brilaps.com || http://wiki.brilaps.com
* @license http://www.opensource.org/licenses/gpl-license.php GNU/GPL v.2.
*/

/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

//unfortunately!
if (phpversion() < 5) {
    mosRedirect( 'index2.php', T_('REST API requires PHP5 or later.') );
}

//Fix to allow compatibility with J!
if (!function_exists( 'T_' )) { function T_($string) {return $string;} }

//If user can administer normal users then they can do the REST users as well
if (!$acl->acl_check( 'administration', 'manage', 'users', $my->usertype, 'components', 'com_users' )) {
	mosRedirect( 'index2.php', T_('You are not authorized to view this resource.') );
}

require_once( $mainframe->getPath( 'admin_html' ) );

$task 	= trim( mosGetParam( $_REQUEST, 'task', null ) );
$cid 	= mosGetParam( $_REQUEST, 'cid', array( 0 ) );
if (!is_array( $cid )) {
	$cid = array ( 0 );
}

switch ($task) {
	case 'view':
 		showUsers( $option );
		break;
	
	case 'edit':
		editUser( intval($cid[0]), $option );
		break;

	case 'editA':
		editUser( $id, $option );
		break;

	case 'save':
 		saveUser( $option );
		break;

	case 'remove':
		removeUsers( $cid, $option );
		break;

	case 'cancel':
		cancelUser( $option );
		break;
		
	case "settings":
		HTML_users::showConfig($option);
		break;

	case "savesettings":
		saveConfig($option);
		break;

	default:
		showUsers( $option );
		break;
}

/**
* Displays list of REST users
* @param - option component option to call
*/
function showUsers( $option ) {
	global $database, $mainframe, $mosConfig_absolute_path, $mosConfig_list_limit;

	$limit 			= $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	$limitstart 	= $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	$search 		= $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	$search 		= $database->getEscaped( trim( strtolower( $search ) ) );
	$where 			= array();

	if (isset( $search ) && $search!= "") {
		$where[] = "(a.developer_name LIKE '%$search%' OR a.contact_email LIKE '%$search%')";
	}

	$query = "SELECT COUNT(a.id)"
	. "\n FROM #__rest AS a";
	$query .= ( count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : '' );
	$database->setQuery( $query );
	$total = $database->loadResult();

	require_once( $mosConfig_absolute_path . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	$query = "SELECT *"
	. "\n FROM #__rest AS a";
	$query .= (count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : "")
	. "\n LIMIT $pageNav->limitstart, $pageNav->limit";
	$database->setQuery( $query );
	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	HTML_users::showUsers( $rows, $pageNav, $search, $option );
}

/**
* Enables editing of RESTful user account.  Used to approve and block users.
* @param uid - id of the REST record to edit
* @param option - component option to call
*/
function editUser( $uid='0', $option='rest' ) {
	global $database;
	
	$query = "SELECT id, developer_name, product_name, web_app_url, contact_email"
		   . ", phone_number, description, rest_key, block, registration_date, approval_date"
		   . " FROM #__rest WHERE id={$uid}";
	$database->setQuery( $query );
	$rows = $database->loadObjectList();
	$row = $rows[0];
	if (empty($row) || $database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	//Build the html select lists
	$lists['block'] = mosHTML::yesnoRadioList( 'block', 'class="inputbox" size="1"', $row->block );
	$lists['approve'] = mosHTML::yesnoRadioList( 'approve', 'class="inputbox" size="1"', 0 );

	HTML_users::edituser( $row, $lists, $option, $uid );
}

/**
* Used to save REST user changes made via edit
* @param option - component option to call
*/
function saveUser( $option ) {
	global $database, $mosConfig_live_site, $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_sitename;
	
	$id = intval(mosGetParam( $_REQUEST, 'id', 0 ));
	$block = intval(mosGetParam( $_REQUEST, 'block', 1 ));
	$approve = intval(mosGetParam( $_REQUEST, 'approve', 0 ));
	
	if ($approve===1) {
		//New approval so update db and send email notification of approval
		$activationCode = md5(mosMakePassword());
		$set = "SET block = {$block}, approval_date = now(), activation = '{$activationCode}'";
	} else {
		//Just update the blocked status
		$set = "SET block = {$block}";
	}
	
	$query = "UPDATE #__rest"
		   . "\n {$set}"
		   . "\n WHERE id = {$id}";
	$database->setQuery( $query );
	if (!$database->query()) {
		die( $database->stderr() );
	}
	
	if ($approve===1) {
		$query = "SELECT contact_email FROM #__rest WHERE id={$id}";
		$database->setQuery( $query );
		$contactEmail = $database->loadResult();
		$activationUrl = $mosConfig_live_site.'/index.php?option=com_rest&task=activate&activation='.$activationCode;
		$subject = sprintf ( T_('%s:: REST API Account Approved'), $mosConfig_sitename);
		$message = sprintf ( T_('The API account you registered for on %s has just been approved by the administrator.  Click on the link below to activate your accout.  The account must be activated before it can utilized.  Upon successful activation you will be sent the unique API key needed for login.

%s

Please do not respond to this message as it is automatically generated and is for information purposes only.'), 
$mosConfig_sitename, $activationUrl);

		$subject = html_entity_decode($subject, ENT_QUOTES);
		$message = html_entity_decode($message, ENT_QUOTES);
		mosMail($mosConfig_mailfrom, $mosConfig_fromname, $contactEmail, $subject, $message);
	}

	$msg = T_('Successfully Saved API User Details');
	mosRedirect( 'index2.php?option='.$option, $msg );
}

/**
* Cancels an edit operation
* @param option component option to call
*/
function cancelUser( $option ) {
	mosRedirect( 'index2.php?option='.$option.'&task=view' );
}

/**
* Removes RESTful user(s) from the database
* @param cid - id(s) of user records to be removed
* @param option - component option to call
*/
function removeUsers( $cid, $option ) {
	global $database;

	if (!is_array($cid) || count($cid)<1) {
		$msg = T_("Select an item to delete");
		mosRedirect( 'index2.php?option='. $option, $msg );
	}

	if (count($cid)) {
		$deleted = array();
		foreach ($cid as $id) {
			$deleted[] = $id;
		}
		if (count($deleted)) {
			$cids = implode(',', $deleted);
			$query = "DELETE FROM #__rest WHERE id IN ($cids)";
			$database->setQuery($query);
			if (!$database->query()) {
				die( $database->stderr() );
			}
		}
	}
	mosRedirect( 'index2.php?option='. $option, $msg );
}

/**
 * @param option
 * @return saves configuration file
 */
function saveConfig($option) {
    global $mosConfig_absolute_path;
	$configfile = $mosConfig_absolute_path."/administrator/components/com_rest/config.rest.php";
	if (!is_writable($configfile)) {
		$mosmsg = T_('REST config file not writable!');
		mosRedirect("index2.php?option=com_rest&task=settings",$mosmsg);
		exit;
	}
	
    $allow_rest_api_access = intval(mosGetParam($_POST, 'allow_rest_api_access', 0));
    $log_api_requests = intval(mosGetParam($_POST, 'log_api_requests', 0));
    $allow_rest_registration = intval(mosGetParam($_POST, 'allow_rest_registration', 0));
    $show_rest_registration_disclaimer = intval(mosGetParam($_POST, 'show_rest_registration_disclaimer', 0));    
	$rest_registration_disclaimer_message = trim(strip_tags(mosGetParam($_POST, 'rest_registration_disclaimer_message', '')));
	
	$config  = "<?php\n";
	$config .= "\$allow_rest_api_access = \"$allow_rest_api_access\";\n";
	$config .= "\$log_api_requests = \"$log_api_requests\";\n";
	$config .= "\$allow_rest_registration = \"$allow_rest_registration\";\n";
	$config .= "\$show_rest_registration_disclaimer = \"$show_rest_registration_disclaimer\";\n";	
	$config .= "\$rest_registration_disclaimer_message = <<<EOD\n$rest_registration_disclaimer_message\nEOD;\n";
	$config .= "?>";
	$fp = @fopen("$configfile", "w");
	if ($fp) {
		fputs($fp, $config, strlen($config));
		fclose ($fp);
	}
	mosRedirect("index2.php?option=rest&task=settings", "Settings saved");
}

?>
